<template>
  <view
    @scroll="onPageScroll"
    v-if="shenheStatus != 1 || !shenheAliStatus"
    :class="[isScroll ? 'disabled' : '']"
  >
    <view :class="['diy-page', hasFoods]" v-if="loading">
      <view :class="'page-container ' + useNav ? 'useFoot' : ''">
        <view class="diy-page-bg" :style="[pageCss]"></view>
        <diyItem
          :ref="'diy' + index"
          v-for="(item, index) in templates"
          :key="index"
          :params="item"
          :location="location"
          :page="page"
          :reloadHeader="reloadHeader"
          :loadMoreProductClassify="canLoadMorePc"
          @classifyToTop="classifyToTop"
          :cash="cash"
        ></diyItem>
        <controls :controlList="controlList"></controls>
        <window
          @changeShow="(e) => (isScroll = e)"
          ref="window"
          :controlList="controlList"
          :params="popData"
        ></window>
        <footNav :controlList="controls" v-if="controls.length"></footNav>
      </view>
    </view>
    <!-- 全局过渡组件 -->
    <transitionPage ref="transitionPage" :show="!loading"></transitionPage>
    <getSuccess
      v-if="showGetCoupon"
      @close="$store.state.showGetCoupon = false"
      :couponInfo="gettedCoupon"
    >
    </getSuccess>

    <!-- #ifdef MP-WEIXIN -->
    <toolsPrivacy ref="toolsPrivacy" className="tabbar"></toolsPrivacy>
    <!-- #endif -->
  </view>
  <Shenhe v-else-if="shenheStatus == 1"></Shenhe>
</template>

<script>
import store from "@/store/index";
import Shenhe from "@/components/shenhe/shenhe";
import diyItem from "@/components/diyNew/index.vue";
import controls from "@/components/diyNew/controls/index.vue";
import window from "@/components/diyNew/window/index.vue";
import footNav from "@/components/diyNew/footNav/index.vue";
import { mapGetters } from "vuex";
import shop from "@/api/shop";
import toolsPrivacy from "@/components/tools/tools-privacy.vue";
import { tabBarData as controlsData } from "@/common/jsonData.js";
import { getStoreSwitch } from "@/api/system";
import { storeAppInfo } from "@/api/login";

export default {
  components: {
    diyItem,
    controls,
    window,
    footNav,
    Shenhe,
    toolsPrivacy
  },
  data() {
    return {
      isScroll: false,
      templates: [],
      page: {},
      controlList: [],
      location: {
        longitude: "",
        latitude: ""
      },
      useNav: false,
      reloadHeader: false,
      canLoadMorePc: false,
      mdId: -1,
      pageScrollTop: 0,
      showAppModal: false, // app端隐私协议弹窗
      // 页面是否加载完毕
      loading: false,

      popData: null,
      hasFoods: "",
      cash: null,
      lan: 0
    };
  },
  computed: {
    ...mapGetters(["getStoreId"]),
    pageCss() {
      if (this.loading) {
        let pageCss = JSON.parse(JSON.stringify(this.page.pageCss));
        if (pageCss?.padding) delete pageCss.padding;
        if (pageCss?.borderRadius) delete pageCss.borderRadius;
        return pageCss;
      } else {
        return "";
      }
    },
    hasProductClassify() {
      if (!this.templates.length) {
        return false;
      } else {
        let tIndex = this.templates.findIndex((d) => {
          return (
            d.comName == "productClassify" || d.comName == "integralProduct"
          );
        });
        if (tIndex > -1) return true;
      }
    },
    hasShowOneReg() {
      const storeId = uni.getStorageSync("store_id");
      return !storeId && this.$store.getters.has_is_one_store;
    }
  },
  onReady() {
    uni.hideTabBar();
  },
  async onLoad(option) {
    if (option.id) {
      let res = await this.$allrequest.alipay.getUpdateMdData({
        md_id: option.id
      });

      if (!res.code && res.data) {
        uni.setStorageSync(
          "storeMdData",
          JSON.stringify({
            id: option.id,
            name: res.data.name,
            mobile: res.data.mobile,
            city_name: res.data.city_name,
            province_name: res.data.province_name,
            district_name: res.data.district_name,
            address: res.data.address,
            cover_url: res.data.cover_url,
            open_status: res.data.open_status,
            shop_time_type: res.data.shop_time_type,
            end_time: res.data.end_time,
            start_time: res.data.start_time,
            latitude: res.data.latitude,
            longitude: res.data.longitude,
            distance: "未知"
          })
        );
      }
    }

    if (option.store_id && parseInt(option.store_id) > 0) {
      this.$store.commit("setStoreId", option.store_id);
    }

    if (this.$store.getters.has_is_one_store) {
      uni.login({
        success: async (r) => {
          const res = await getStoreSwitch({
            code: r.code
          });
          if (res.code) return;
          let { token, is_switch_store, store_id, copyright } = res.data;
          if (is_switch_store) {
            uni.removeStorageSync("storeMdData");
            this.$store.commit("setStoreId", store_id);
            this.$store.commit("setCopyright", copyright);
          }
          if (token) {
            this.$utils.setStorage("token", token);
          }
        }
      });
    }

    let storageMd = uni.getStorageSync("storeMdData");
    if (storageMd) {
      storageMd = JSON.parse(storageMd);
      this.mdId = storageMd.id;
    }
    if (!this.hasShowOneReg) {
      this.getIndexPageDiy();
    }

    // #ifdef MP-WEIXIN
    this.$nextTick(() => {
      let SDKVersion = uni.getStorageSync("SDKVersion");

      if (this.$utils.compare("3.0.2", SDKVersion)) {
        this.$refs.toolsPrivacy.hasShowPrivacySetting();
      }
    });
    // #endif
  },
  async onShow() {
    uni.setNavigationBarTitle({
      title: " "
    });
    // if (uni.getStorageSync("dandianpu")) {
    //   this.getIndexPageDiy();
    //   let res = await this.$allrequest.alipay.getUpdateMdData({ md_id: "" });

    //   if (!res.code && res.data) {
    //     uni.setStorageSync(
    //       "storeMdData",
    //       JSON.stringify({
    //         id: uni.getStorageSync("store_id"),
    //         name: res.data.name,
    //         mobile: res.data.mobile,
    //         city_name: res.data.city_name,
    //         province_name: res.data.province_name,
    //         district_name: res.data.district_name,
    //         address: res.data.address,
    //         cover_url: res.data.cover_url,
    //         open_status: res.data.open_status,
    //         shop_time_type: res.data.shop_time_type,
    //         end_time: res.data.end_time,
    //         start_time: res.data.start_time,
    //         latitude: res.data.latitude,
    //         longitude: res.data.longitude,
    //         distance: "未知"
    //       })
    //     );
    //   }

    //   uni.removeStorageSync("dandianpu");
    // }

    // 判断是否登录
    const isLogin = this.$utils.isLogin(false);
    if (!isLogin) {
      this.$store.commit("setNoLoginTabarPath", "/pages/home/home");
      this.$store.commit("setRouteType", "switchtab");
    }
    this.reloadHeader = true;
    setTimeout(() => {
      this.reloadHeader = false;
    }, 200);
    let storageMd = uni.getStorageSync("storeMdData");
    let mdDataReload = uni.getStorageSync("MdDataReload");
    if (mdDataReload) {
      this.page = {};
      this.loading = false;
      setTimeout(() => {
        this.getIndexPageDiy();
        uni.removeStorageSync("MdDataReload");
      }, 0);
      return;
    }
    if (storageMd && mdDataReload) {
      storageMd = JSON.parse(storageMd);
      this.page = {};
      this.loading = false;
      setTimeout(() => {
        this.getIndexPageDiy();
        uni.removeStorageSync("MdDataReload");
      }, 0);
    }
    if (uni.getStorageSync("food_table_num")) {
      uni.removeStorageSync("food_table_num");
    }
    if (uni.getStorageSync("flag_id")) {
      uni.removeStorageSync("flag_id");
    }

    this.init();
    this.getDefultStore();
    // #ifdef APP-PLUS
    this.checkAndroidUpdate();
    // #endif
  },

  watch: {
    getStoreId: {
      async handler(e) {
        if (e) {
          this.getIndexPageDiy();
          shop
            .getInfo({
              store_id: e
            })
            .then((res) => {
              if (!res.code && res.data.name) {
                uni.setStorageSync("storeName", res.data.name);
              }
            });
        }
      },
      immediate: true
    },
    lan: function (newVal, oldVal) {
      if (newVal >= 200) {
        this.cash = 1;
        return;
      } else {
        this.cash = 2;
        return;
      }
    }
  },

  onShareAppMessage() {
    const storeId = uni.getStorageSync("store_id");
    const userInfo = uni.getStorageSync("userInfo");
    const storeMdData = uni.getStorageSync("storeMdData");

    return {
      title: this.stores.store_share_title || uni.getStorageSync("storeName"),
      path:
        `/pages/home/home?store_id=${storeId}&user_id=` +
        (userInfo && userInfo.id > 0 ? userInfo.id : 0) +
        "&id=" +
        (storeMdData ? JSON.parse(storeMdData).id : 0) +
        "&page_type=3",
      imageUrl: this.stores.store_share_logo || uni.getStorageSync("logo"),
      desc: this.stores.store_share_desc,
      success(res) {
        uni.showToast({
          title: that.$t("home.success")
        });
      },
      fail(res) {
        uni.showToast({
          title: that.$t("home.fail"),
          icon: "none"
        });
      }
    };
  },
  onReachBottom() {
    if (!this.hasProductClassify) return;
    this.canLoadMorePc = true;
    setTimeout(() => {
      this.canLoadMorePc = false;
    }, 10);
  },
  onPullDownRefresh() {
    this.templates = [];
    this.controlList = [];
    this.controls = [];
    this.$refs.transitionPage.init();
    this.getIndexPageDiy();
  },

  methods: {
    onPageScroll(e) {
      this.lan = e.scrollTop;
    },
    async checkAndroidUpdate() {
      const res = await storeAppInfo();
      if (res.code != 0) {
        return;
      }
      let version = res.data.app_store_android_version;
      let download_url = res.data.app_store_android;
      if (!version || !download_url) {
        return;
      }
      if (parseInt(version) > 0) {
        let current_version = plus.runtime.versionCode;
        if (current_version < version) {
          uni.showModal({
            title: "更新提醒",
            showCancel: false,
            content: "您现在版本" + current_version + "，发现新版本，请更新!",
            success: (res) => {
              if (res.confirm) {
                plus.nativeUI.showWaiting("下载更新文件...");
                let downloadTask = uni.downloadFile({
                  url: download_url,
                  complete: () => {},
                  success: (res1) => {
                    plus.nativeUI.closeWaiting();
                    if (res1.statusCode == 200) {
                      // 安装
                      plus.nativeUI.showWaiting("安装中...");
                      plus.runtime.install(
                        res1.tempFilePath,
                        function () {
                          plus.nativeUI.closeWaiting();
                          plus.nativeUI.alert("更新成功!", function () {
                            plus.runtime.restart();
                          });
                        },
                        function (e) {
                          plus.nativeUI.closeWaiting();
                          plus.nativeUI.alert("更新失败");
                          // 删除临时目录
                          if (e.code == 10) {
                            uni.removeSavedFile({
                              filePath: res1.tempFilePath
                            });
                          }
                        }
                      );
                    }
                  },
                  fail(res) {
                    plus.nativeUI.closeWaiting();
                    plus.nativeUI.alert("下载失败");
                  }
                });
              }
            }
          });
        }
      }
    },
    getDefultStore() {
      this.$allrequest.publicMethod.defaultStore({}).then((res) => {
        if (res.code == 0) {
          this.$store.commit("setStores", res.data.store);
          this.$store.commit("setImages", res.data.images);
          this.$store.commit("setShareSetting", res.data.share_setting);
          this.$store.commit(
            "setOneStoreSwitchStore",
            res.data.one_store_switch_store
          );
          this.$store.commit("setCopyright", res.data.copyright);
        }
      });
    },

    // 获取diy首页配置数据
    getIndexPageDiy() {
      this.$allrequest.diyNew.getDiyIndexPage({}, true).then((res) => {
        if (!res.code) {
          let data = res.data.template;
          data = JSON.parse(data.template);

          try {
            if (data && data.templates && data.templates.length) {
              let item = data.templates.find(
                (el) => el.comName === "diySearch"
              );
              if (item) {
                uni.setStorageSync("hasSearchTop", item.params.fixedTop);
              }
            }
          } catch (error) {}

          this.page = data;
          if (res.data.store_name && res.data.store_logo) {
            this.page.store_name = res.data.store_name;
            this.page.store_logo = res.data.store_logo;
          }
          this.loading = true;
          this.templates = data.templates;

          res.data.controls = JSON.parse(res.data.controls);
          // 审核状态使用固定导航栏
          if (this.shenheStatus == 1) {
            res.data.controls = controlsData;
          }
          this.controlList = res.data.controls;

          this.popData = res.data.controls.find(
            (el) => el.controlComName === "widgetPopupControl"
          );
          this.$store.commit("setControls", res.data.controls);
          let [footNav] = this.controlList.filter((d) => {
            return d.show_type == "nav";
          });
          if (footNav && footNav.is_show) {
            this.useNav = true;
          }

          this.init();
          uni.stopPullDownRefresh();
        }
      });
    },
    classifyToTop(e) {
      // let top = e.nodeTop + this.pageScrollTop;
      // top = top - 50;
      // uni.pageScrollTo({
      //   scrollTop: top,
      //   duration: 300
      // });
    },

    init() {
      this.$nextTick(() => {
        const indexs = [];
        if (this.templates && this.templates.length) {
          this.templates.forEach((el, i) => {
            if (["newUserCoupon", "pageHeader"].includes(el.comName)) {
              indexs.push(i);
            }
          });

          let foods = this.templates.filter(
            (el) => el.comName === "orderingFood"
          );
          if (foods && foods.length) {
            this.hasFoods = "foods";
          }
        }

        if (indexs.length) {
          indexs.forEach((el, i) => {
            let str = `diy${el}`;
            if (this.$refs[str][i]) {
              this.$refs[str][i].init();
            }
          });
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.diy-page {
  width: 100%;
  min-height: 100vh;
  overflow-y: auto;
  position: relative;

  &.foods {
    padding-bottom: calc(100rpx);
    padding-bottom: calc(100rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(100rpx + env(safe-area-inset-bottom));
  }

  .page-container {
    width: 100%;
    position: relative;
  }

  .diy-page-bg {
    width: 100%;
    height: 100%;
    z-index: -1;
    position: fixed;
    left: 0;
    top: 0;
  }
}

.useFoot {
  padding-bottom: calc(120rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
}

.disabled {
  height: 100vh;
  overflow: hidden;
}
</style>
